package com.hckjsec.cloud.controller;

import com.alibaba.fastjson.JSON;
import com.hckjsec.cloud.WebSocket.WebSocketServer;
import com.hckjsec.cloud.domain.AppletsBusinessVideo;
import com.hckjsec.cloud.domain.AppletsBusinessVideoSign;
import com.hckjsec.cloud.domain.AppletsBusinessVideoSigncoor;
import com.hckjsec.cloud.domain.videoView.QysCallbackView;
import com.hckjsec.cloud.domain.view.BasicView;
import com.hckjsec.cloud.domain.view.QysView;
import com.hckjsec.cloud.service.IAppletsBusinessVideoService;
import com.hckjsec.cloud.service.IAppletsBusinessVideoSignService;
import com.hckjsec.cloud.service.IAppletsBusinessVideoSigncoorService;
import com.hckjsec.common.core.domain.AjaxResult;
import com.hckjsec.common.init.YwInitData;
import com.hckjsec.common.utils.StringUtils;
import com.hckjsec.common.utils.http.RequestUtil;
import com.qiyuesuo.sdk.v2.SdkClient;
import com.qiyuesuo.sdk.v2.utils.CryptUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicReference;

//处理回调信息
@RestController
@RequestMapping("/cloud/callback/api")
public class WxPublicCloudCallBackApiController {
    @Autowired
    private YwInitData ywInitData;

    @Autowired
    private IAppletsBusinessVideoService appletsBusinessVideoService;

    @Autowired
    private IAppletsBusinessVideoSignService appletsBusinessVideoSignService;

    @Autowired
    private IAppletsBusinessVideoSigncoorService appletsBusinessVideoSigncoorService;
    //契约锁返回信息处理
    @PostMapping("/qiyuesuoResult")
    public String qiyuesuoResult(HttpServletRequest req) throws Exception
    {
        String content = StringUtils.isHcNull(req.getParameter("content"),"");
        String configId = StringUtils.isHcNull(req.getParameter("configId"),"");
        if("".equals(configId)){
            return "SUCCESS";
        }
        BasicView basicView= JSON.parseObject(JSON.toJSONString(ywInitData.getIdByBasicViewMap().get(Long.valueOf(configId))),BasicView.class);
        if (StringUtils.isNull(basicView)){
            return "SUCCESS";
        }
        QysView qysView=basicView.getQys();
        if (StringUtils.isNull(qysView)){
            return "SUCCESS";
        }
        SdkClient client = new SdkClient(qysView.getUrl(), qysView.getAccesskey(), qysView.getAccessSecret());
        String msg= CryptUtils.aesDerypt(content, qysView.getCallbackDecryptKey());
        QysCallbackView qysCallbackView=JSON.parseObject(msg,QysCallbackView.class);
        if ("SIGNING".equals(qysCallbackView.getContractStatus())){//用户单独签字完成
            AppletsBusinessVideoSign appletsBusinessVideoSign = new AppletsBusinessVideoSign();
            appletsBusinessVideoSign.setContractid(qysCallbackView.getContractId());
            List<AppletsBusinessVideoSign> appletsBusinessVideoSignList = appletsBusinessVideoSignService.selectAppletsBusinessVideoSignList(appletsBusinessVideoSign);
            String username=StringUtils.isHcNull(qysCallbackView.getTenantName(),"");
            if (!"".equals(username)){
                AtomicReference<Long> videoId= new AtomicReference<>(0L);
                appletsBusinessVideoSignList.forEach(kv->{
                    videoId.set(kv.getVideoid());
                    List<AppletsBusinessVideoSigncoor> appletsBusinessVideoSigncoorList=appletsBusinessVideoSigncoorService.selectAppletsBusinessVideoSigncoorList(new AppletsBusinessVideoSigncoor(kv.getUuid(),username));
                    appletsBusinessVideoSigncoorList.forEach(signcoor->{
                        signcoor.setState("1");
                        appletsBusinessVideoSigncoorService.updateAppletsBusinessVideoSigncoor(signcoor);
                    });
                });
                AppletsBusinessVideo appletsBusinessVideo=appletsBusinessVideoService.selectAppletsBusinessVideoById(videoId.get());
                WebSocketServer.sendSignMsg(appletsBusinessVideo.getRoomid(),username);
            }
        }else if("COMPLETE".equals(qysCallbackView.getContractStatus())){
            AppletsBusinessVideoSign appletsBusinessVideoSign = new AppletsBusinessVideoSign();
            appletsBusinessVideoSign.setContractid(qysCallbackView.getContractId());
            List<AppletsBusinessVideoSign> appletsBusinessVideoSignList = appletsBusinessVideoSignService.selectAppletsBusinessVideoSignList(appletsBusinessVideoSign);
            AtomicReference<Long> videoId= new AtomicReference<>(0L);
            appletsBusinessVideoSignList.forEach(kv->{
                videoId.set(kv.getVideoid());
                kv.setState("1");
                appletsBusinessVideoSignService.updateAppletsBusinessVideoSign(kv);
                List<AppletsBusinessVideoSigncoor> appletsBusinessVideoSigncoorList=appletsBusinessVideoSigncoorService.selectAppletsBusinessVideoSigncoorList(new AppletsBusinessVideoSigncoor(kv.getUuid()));
                appletsBusinessVideoSigncoorList.forEach(signcoor->{
                    signcoor.setState("1");
                    appletsBusinessVideoSigncoorService.updateAppletsBusinessVideoSigncoor(signcoor);
                });
            });
            String username=StringUtils.isHcNull(qysCallbackView.getTenantName(),"");
            if (!"".equals(username)){
                AppletsBusinessVideo appletsBusinessVideo=appletsBusinessVideoService.selectAppletsBusinessVideoById(videoId.get());
                WebSocketServer.sendSignMsg(appletsBusinessVideo.getRoomid(),username);
            }
        }
        return "SUCCESS";
    }

    //契约锁返回信息处理
    @PostMapping("/callVideoResult")
    public AjaxResult callVideoResult(HttpServletRequest req) throws Exception
    {
        String videoResult = RequestUtil.getReqInputStreamParam(req);
        if(!videoResult.equals("")){
            Map<String,String> resultHT = JSON.parseObject(videoResult, Hashtable.class);
            if (resultHT.containsKey("stream_id")){
                String stream_id=StringUtils.isHcNull(resultHT.get("stream_id"),"");
                String video_url=StringUtils.isHcNull(resultHT.get("video_url"),"");
                if (!"".equals(stream_id) && !"".equals(video_url)){
                    AppletsBusinessVideo appletsBusinessVideo=new AppletsBusinessVideo();
                    appletsBusinessVideo.setRecordingid(stream_id);
                    List<AppletsBusinessVideo> appletsBusinessVideoList=appletsBusinessVideoService.selectAppletsBusinessVideoList(appletsBusinessVideo);
                    appletsBusinessVideoList.forEach(kv->{
                        kv.setVideoUrl(video_url);
                        appletsBusinessVideoService.updateAppletsBusinessVideo(kv);
                    });
                }
            }
        }
        return AjaxResult.success();
    }
}
